/*
 * Copyright 2012-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.security.reactive;

import java.util.function.Supplier;

import reactor.core.publisher.Mono;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;

/**
 * 基于 {@link ApplicationContext} 的 {@link ServerWebExchangeMatcher}。可以直接使用
 * {@link ApplicationContext}，获取已有的 Bean，或通过
 * {@link AutowireCapableBeanFactory#createBean(Class, int, boolean) 创建一个新的 Bean}，
 * 并以常规方式进行自动装配。
 *
 * @param <C> 实际匹配方法所需的上下文类型。可以是 {@link ApplicationContext}，也可以是
 * {@link ApplicationContext#getBean(Class) 获取的已有 Bean} 的类型。
 * @author Madhura Bhave
 * @since 2.0.0
 */
public abstract class ApplicationContextServerWebExchangeMatcher<C> implements ServerWebExchangeMatcher {

	private final Class<? extends C> contextClass;

	private volatile Supplier<C> context;

	private final Object contextLock = new Object();

	public ApplicationContextServerWebExchangeMatcher(Class<? extends C> contextClass) {
		Assert.notNull(contextClass, "Context class must not be null");
		this.contextClass = contextClass;
	}

	@Override
	public final Mono<MatchResult> matches(ServerWebExchange exchange) {
		if (ignoreApplicationContext(exchange.getApplicationContext())) {
			return MatchResult.notMatch();
		}
		return matches(exchange, getContext(exchange));
	}

	/**
	 * 判断策略实现的规则是否匹配给定的交换对象。
	 * @param exchange 源交换对象
	 * @param context 已初始化上下文的提供者（可能会抛出异常）
	 * @return 是否匹配
	 */
	protected abstract Mono<MatchResult> matches(ServerWebExchange exchange, Supplier<C> context);

	/**
	 * 判断是否应该忽略该 {@link ApplicationContext}，不用于匹配。
	 * 如果返回 {@code true}，则不会使用该上下文，{@link #matches(ServerWebExchange)} 返回 {@code false}。
	 * @param applicationContext 待判断的应用上下文
	 * @return 是否忽略该上下文
	 * @since 2.2.5
	 */
	protected boolean ignoreApplicationContext(ApplicationContext applicationContext) {
		return false;
	}

	protected Supplier<C> getContext(ServerWebExchange exchange) {
		if (this.context == null) {
			synchronized (this.contextLock) {
				if (this.context == null) {
					Supplier<C> createdContext = createContext(exchange);
					initialized(createdContext);
					this.context = createdContext;
				}
			}
		}
		return this.context;
	}

	/**
	 * 上下文初始化完成后调用。
	 * @param context 已初始化上下文的提供者（可能会抛出异常）
	 */
	protected void initialized(Supplier<C> context) {
	}

	@SuppressWarnings("unchecked")
	private Supplier<C> createContext(ServerWebExchange exchange) {
		ApplicationContext context = exchange.getApplicationContext();
		Assert.state(context != null, "No ApplicationContext found on ServerWebExchange.");
		if (this.contextClass.isInstance(context)) {
			return () -> (C) context;
		}
		return () -> context.getBean(this.contextClass);
	}

}
